﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using DBEntity;
using iver.Entity;

namespace iver.Controllers
{
    public class RoleController : ApiController
    {
        /// <summary>
        /// 得到自己能用的模块，用于添加角色
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public ResResult BaseModuleList([FromBody]ReqList req)
        {
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            List<DBEntity.sysModule> arr = Help.BaseModuleList(authInfo);
            int count = arr.Count();
            return new ResResult
            {
                success = true,
                result = new
                {
                    count,
                    arr
                },
            };
  
        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public ResResult RoleList([FromBody]ReqList req)
        {
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            iverDB db = new iverDB();

            var roleList = (from u in db.sysRole
                            join uu in db.sysUser on u.createBy equals uu.id into temp1
                            from fuser in temp1.DefaultIfEmpty()
                            where authInfo.isSuperAdmin ? 1 == 1 : u.createBy == authInfo.userId
                            orderby u.id descending
                            select new
                            {
                                u.id,
                                u.createTime,
                                u.createBy,
                                u.isEnable,
                                u.remark,
                                u.roleName,
                                fuserName = fuser.userName,
                                ftrueName = fuser.trueName,
                            });
            var arr = roleList.Skip(req.limit * (req.page - 1)).Take(req.limit);
            int count = roleList.Count();

            return new ResResult
            {
                success = true,
                result = new
                {
                    count,
                    arr,
                },
            };
        }
        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public ResResult RoleModuleList([FromBody]ReqListQuery req)
        {
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            iverDB db = new iverDB();

            var list = (from u in db.sysRoleModule
                        where req.id == u.roleId
                        orderby u.id descending
                        select u);
            var arr = list.Skip(req.limit * (req.page - 1)).Take(req.limit);
            int count = list.Count();

            return new ResResult
            {
                success = true,
                result = new
                {
                    count,
                    arr,
                },
            };
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public ResResult RoleAdd([FromBody]sysRole req)
        {
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            DateTime now = DateTime.Now;
            req.createTime = now;
            req.createBy = authInfo.userId;
            iverDB db = new iverDB();
            db.sysRole.Add(req);
            db.SaveChanges();
            return new ResResult
            {
                success = true,
                rescode = ResCode.SuccessAdd,
                result = new
                {
                    id = req.id,
                },
            };
            //iverDB db = new iverDB();
            ////添加角色表
            //sysRole role = db.sysRole.Add(new sysRole()
            //{
            //    createBy = authInfo.userId,
            //    createTime = DateTime.Now,
            //    isEnable = req.isEnable,
            //    remark = req.remark,
            //    roleName = req.roleName,
            //});
            //int addRoleCount = db.SaveChanges();
            ////添加关系表
            //List<sysRoleModule> RoleModuleList = new List<sysRoleModule>();
            //for (int i = 0; i < req.moduleIdList.Count; i++)
            //{
            //    RoleModuleList.Add(new sysRoleModule()
            //    {
            //        moduleId = req.moduleIdList[i],
            //        roleId = role.id,
            //    });
            //}
            //db.sysRoleModule.AddRange(RoleModuleList);
            //int addRoleModuleCount = db.SaveChanges();

            //return new ResResult
            //{
            //    success = true,
            //    rescode = ResCode.SuccessAdd,
            //    result = new
            //    {
            //        roleId = role.id,
            //        addRoleCount,
            //        addRoleModuleCount,
            //    },
            //};
        }
        /// <summary>
        /// 
        /// </summary>
        public class RoleModule : sysRole
        {
            /// <summary>
            /// 
            /// </summary>
            public List<int> moduleIdList;
        }
        /// <summary>
        /// 角色模块添加-添加角色使用
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public ResResult RoleModuleAdd([FromBody]RoleModule req)
        {
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            iverDB db = new iverDB();

            List<sysRoleModule> RoleModuleList = new List<sysRoleModule>();
            for (int i = 0; i < req.moduleIdList.Count; i++)
            {
                RoleModuleList.Add(new sysRoleModule()
                {
                    moduleId = req.moduleIdList[i],
                    roleId = req.id,
                });
            }
            db.sysRoleModule.AddRange(RoleModuleList);
            int addRoleModuleCount = db.SaveChanges();

            return new ResResult
            {
                success = true,
                rescode = ResCode.SuccessAdd,
                result = new
                {
                    addRoleModuleCount
                },
            };
        }
        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public ResResult RoleEdit([FromBody]RoleModule req)
        {
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            iverDB db = new iverDB();
            sysRole model = db.sysRole.FirstOrDefault(u => u.id == req.id);
            if (model == null)
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailParams,
                };
            }
            //开启事务
            var tran = db.Database.BeginTransaction();
            try
            {
                //删除关系表
                int roleId = model.id;
                var listRoleModule = db.sysRoleModule.Where(u => u.roleId == roleId);
                db.sysRoleModule.RemoveRange(listRoleModule);

                //添加关系表
                List<sysRoleModule> RoleModuleList = new List<sysRoleModule>();
                for (int i = 0; i < req.moduleIdList.Count; i++)
                {
                    RoleModuleList.Add(new sysRoleModule()
                    {
                        moduleId = req.moduleIdList[i],
                        roleId = roleId,
                    });
                }
                db.sysRoleModule.AddRange(RoleModuleList);

                model.roleName = req.roleName == null ? model.roleName : req.roleName;
                model.remark = req.remark == null ? model.remark : req.remark;
                model.isEnable = req.isEnable == null ? model.isEnable : req.isEnable;
                int changeCount = db.SaveChanges();
                //提交事务
                tran.Commit();
                return new ResResult
                {
                    success = true,
                    rescode = ResCode.SuccessEdit,
                    result = new
                    {
                        delRoleModuleCount = listRoleModule.Count(),
                        addRoleModuleCount = RoleModuleList.Count(),
                        changeCount,
                    },
                };
            }
            catch (Exception ex)
            {
                tran.Rollback();
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailCatch,
                    result = ex.Message,
                };
            }

        }
        /// <summary>
        /// 删除角色 和删除角色模块
        /// </summary>
        /// <param name="req">id数组</param>
        /// <returns></returns>
        [HttpPost]
        public ResResult RoleDel([FromBody]ReqID<List<int>> req)
        {
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            iverDB db = new iverDB();
            //删除角色表
            var listRole = db.sysRole.Where(u => req.id.Contains(u.id));
            int delRoleCount = listRole.Count();
            //没有删除任何数据，视为错误
            if (delRoleCount == 0)
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailParams,
                };
            }
            //开启事务
            var tran = db.Database.BeginTransaction();
            try
            {
                db.sysRole.RemoveRange(listRole);
                int delRoleModuleCount = 0;
                //删除关系表
                for (int i = 0; i < delRoleCount; i++)
                {
                    int roleId = listRole.ToList()[i].id;
                    var listRoleModule = db.sysRoleModule.Where(u => u.roleId == roleId);
                    db.sysRoleModule.RemoveRange(listRoleModule);
                    delRoleModuleCount += listRoleModule.Count();
                }
                int changeCount = db.SaveChanges();
                //提交事务
                tran.Commit();
                return new ResResult
                {
                    success = true,
                    rescode = ResCode.SuccessDel,
                    result = new
                    {
                        delRoleCount,
                        delRoleModuleCount,
                        changeCount,
                    },
                };
            }
            catch (Exception ex)
            {
                tran.Rollback();
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailCatch,
                    result = ex.Message,
                };
            }

        }
    }
}